package com.skj.server;

import javax.jdo.* ;
import com.google.appengine.api.datastore.* ;

public class UserDatabase
{
	private final PersistenceManagerFactory pmfInstance ;

    public UserDatabase()
    {
    	pmfInstance = JDOHelper.getPersistenceManagerFactory("transactions-optional");
    }
    
    public void createUserRecord(com.google.appengine.api.users.User user)
    {
    	UserRecord userRecord = new UserRecord(user) ;
    	
    	PersistenceManager pm = pmfInstance.getPersistenceManager();
    	
    	try
    	{
            pm.makePersistent(userRecord) ;
        }
    	finally
    	{
            pm.close();
        }
    }
    
    public UserRecord retrieveUserRecord(com.google.appengine.api.users.User user)
    {
    	PersistenceManager pm = pmfInstance.getPersistenceManager();
    	UserRecord userRecord ;
    	
    	try
    	{
    		userRecord = pm.getObjectById(UserRecord.class, user.getUserId());
        }
    	catch(Exception e)
    	{
    		userRecord = null ;
    	}
    	finally
    	{
            pm.close();
        }
    	
    	return userRecord ;
    }
    
    public void updateUserRecord(com.google.appengine.api.users.User user)
    {
    	PersistenceManager pm = pmfInstance.getPersistenceManager();
    	
    	try
    	{
    		UserRecord userRecord = pm.getObjectById(UserRecord.class, user.getUserId());
    		
    		//UserRecord.setContent(content) ;
    		// Will be used when using custom fields
    		
    		pm.makePersistent(userRecord) ;
        }
    	finally
    	{
            pm.close();
        }
    }
    
    public void deleteUserRecord(com.google.appengine.api.users.User user)
    {
    	PersistenceManager pm = pmfInstance.getPersistenceManager();
    	
    	try
    	{
    		UserRecord userRecord = pm.getObjectById(UserRecord.class, user.getUserId());
    		pm.deletePersistent(userRecord);
        }
    	finally
    	{
            pm.close();
        }
    }
}
